#!/bin/bash
set -e

# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

# 错误处理函数
handle_error() {
    log "ERROR: $1"
    exit 1
}

# 信号处理函数
cleanup() {
    log "Received shutdown signal, cleaning up..."
    if [ ! -z "$FRONTEND_PID" ]; then
        kill $FRONTEND_PID 2>/dev/null || true
    fi
    if [ ! -z "$BACKEND_PID" ]; then
        kill $BACKEND_PID 2>/dev/null || true
    fi
    exit 0
}

# 设置信号处理
trap cleanup SIGTERM SIGINT

# 检查数据库目录
if [ ! -d "/app/data" ]; then
    log "Creating data directory..."
    mkdir -p /app/data
fi

# 检查是否需要启动开发模式（前后端分离）
if [ "$DEV_MODE" = "true" ]; then
    log "Starting in development mode with separate frontend server..."
    
    # 检查Node.js是否可用
    if command -v node >/dev/null 2>&1; then
        log "Starting frontend development server on port 3000..."
        cd /app/frontend || handle_error "Failed to change to frontend directory"
        
        # 检查package.json是否存在
        if [ ! -f "package.json" ]; then
            handle_error "package.json not found in frontend directory"
        fi
        
        npm run dev &
        FRONTEND_PID=$!
        cd /app || handle_error "Failed to change back to app directory"
        
        # 等待前端启动
        log "Waiting for frontend to start..."
        sleep 5
        
        log "Starting backend server on port 8000..."
        python -m uvicorn backend.main:app --host 0.0.0.0 --port 8000 --reload &
        BACKEND_PID=$!
        
        log "Both servers started. PIDs: Frontend=$FRONTEND_PID, Backend=$BACKEND_PID"
        
        # 等待任一服务退出
        wait $FRONTEND_PID $BACKEND_PID
    else
        log "Node.js not found, starting backend only..."
        python -m uvicorn backend.main:app --host 0.0.0.0 --port 8000 --reload
    fi
else
    log "Starting in production mode (backend serves frontend)..."
    
    # 检查后端目录
    if [ ! -d "/app/backend" ]; then
        handle_error "Backend directory not found"
    fi
    
    # 生产模式：后端服务前端静态文件
    log "Starting production server..."
    python -m uvicorn backend.main:app --host 0.0.0.0 --port 8000 --workers 1
fi